package com.slipper.system.message.service;

import java.util.Arrays;
import java.util.List;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.slipper.common.util.StringUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import com.slipper.system.message.dao.MessageDao;
import com.slipper.system.api.message.bo.MessageBO;

import com.slipper.common.transaction.ReadTransactional;
import com.slipper.common.transaction.WriteTransactional;
import com.slipper.common.util.Tool;

@Service
@ReadTransactional
public class MessageService {
    @Resource
    private MessageDao messageDao;
    
    public MessageBO queryBy(String id) {
        return messageDao.queryBy(id);
    }
    
    public List<MessageBO> queryList(MessageBO bo) {
        return messageDao.queryList(bo);
    }
    
    public PageInfo<MessageBO> queryPage(MessageBO bo) {
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(messageDao.queryList(bo));
    }

    public PageInfo<MessageBO> queryMyPage(MessageBO bo) {
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(messageDao.queryMyList(bo));
    }

    public Long queryMyCount(MessageBO bo) {
        return new PageInfo<>(messageDao.queryMyList(bo)).getTotal();
    }
    
    @WriteTransactional
    public int save(MessageBO bo) {
        int result;
        if (bo.getId() != null && !"".equals(bo.getId())) {
            result = messageDao.update(bo);
        } else {
            bo.setId(Tool.getUUID());
            result = messageDao.insert(bo);
        }

        // 删除接收人信息
        messageDao.deleteRead(bo.getId());

        // 保存接收人信息
        if (MessageBO.RECEIVE_TYPE_PART.equals(bo.getReceiveType()) && StringUtil.isNotBlank(bo.getEmployeeIds())) {
            Arrays.stream(bo.getEmployeeIds().split(","))
                    .forEach(employeeId -> messageDao.insertStatus(Tool.getUUID(), bo.getId(), employeeId));
        }
        return result;
    }
    
    @WriteTransactional
    public int delete(MessageBO bo) {
        if (StringUtil.isNotBlank(bo.getId())) {
            messageDao.deleteRead(bo.getId());
        }
        if (bo.getIds() != null && bo.getIds().length > 0) {
            Arrays.stream(bo.getIds()).forEach(id -> messageDao.deleteRead(id));
        }
        return messageDao.delete(bo);
    }

    @WriteTransactional
    public int updateRead(MessageBO bo) {
        if (StringUtil.isNotBlank(bo.getId())) {
            return messageDao.updateRead(Tool.getUUID(), bo.getId(), bo.getEmployeeId());
        }
        if (bo.getIds() != null && bo.getIds().length > 0) {
            Arrays.stream(bo.getIds()).forEach(id -> messageDao.updateRead(Tool.getUUID(), id, bo.getEmployeeId()));
        }
        return 1;
    }
}
